<template>
	<view class="collection-page">
		<view class="header">
			<text class="title">我的收藏</text>
		</view>

		<!-- <view class="attraction-list">
      <travel-card 
        v-for="item in attractions" 
        :key="item.attractionId"
        v-bind="item"
        :tags="['收藏']"
        @click="handleCardClick(item.attractionId)"
      />
    </view> -->
		<!-- <view class="attraction-grid">
			<view class="grid-row" v-for="(row, index) in chunkedAttractions" :key="index">
				<travel-card v-for="item in row" class="grid-item" :key="item.attractionId" v-bind="item" :tags="['收藏']"
					@click="handleCardClick(item.attractionId)" />
			</view>
		</view> -->

		<scroll-view scroll-y class="scroll-container" @scrolltolower="onScrollToLower">
			<view class="attraction-grid">
				<view class="grid-row" v-for="(row, index) in chunkedAttractions" :key="index">
					<travel-card v-for="item in row" class="grid-item" :key="item.attractionId" v-bind="item"
						:tags="['收藏']" @click="handleCardClick(item.attractionId)" />
				</view>
			</view>

			<!-- 加载更多提示 -->
			<view class="load-more" v-if="loading">
				   <text>加载中...</text>
				    <!-- 或者使用自定义加载动画 -->
				    <view class="loading-spinner"></view>
			</view>
			<view class="load-more" v-else-if="noMore">
				<text>没有更多了</text>
			</view>
			<view class="load-more" v-else-if="attractions.length > 0">
				<text>上拉加载更多</text>
			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-if="!loading && attractions.length === 0">
				<image src="/static/images/empty-collection.png" mode="aspectFit"></image>
				<text>暂无收藏景点</text>
			</view>
		</scroll-view>


	</view>
</template>


<script>
	import travelCard from '../index/comment/travelCard.vue';
	import {
		getParams
	} from '@/axios/http';
	import {
		ElMessage
	} from 'element-plus';
	// import base from '@/axios/base.js'

	export default {
		components: {
			travelCard
		},
		data() {
			return {
				attractions: [], // 从后端获取的收藏景点数据
				isNavigating: false, // 添加跳转锁
				loading: false, // 是否正在加载
				noMore: false, // 是否没有更多数据
				lastId: 0, // 当前列表最大ID，用于分页
				limit: 6 // 每次请求数量
			}
		},
		computed: {
			// 将景点数组分割成每行两个的二维数组
			chunkedAttractions() {
				const chunkSize = 2;
				const result = [];
				for (let i = 0; i < this.attractions.length; i += chunkSize) {
					result.push(this.attractions.slice(i, i + chunkSize));
				}
				return result;
			},
			// 获取当前列表中的最大ID
			MaxId() {
				if (this.attractions.length === 0) return 0;
				return Math.max(...this.attractions.map(item => item.attractionId));
			}
		},
		async onLoad() {
			// 模拟从后端获取收藏景点数据
			await this.fetchCollectionData()
		},
		methods: {

			// 构建请求参数
			buildRequestParams() {
				return {
					userId: uni.getStorageSync('LoginUser').userId,
					lastId: this.MaxId,
					limit: this.limit
				};
			},

			async fetchCollectionData() {
				if (this.loading) return;

				this.loading = true;
				this.noMore = false;

				try {
					const data = this.buildRequestParams();
					// console.log("要发送请求的数据：",data)
					const response = await getParams('/userFavorites', data);
					// console.log("收到的返回值：",response)
					if (response.data.code === 200) {
						this.attractions = response.data.attractions || [];
						if (response.data.attractions.length < this.limit) {
							this.noMore = true;
						}
					} else {
						uni.showToast({
							title: response.data.message || '获取收藏列表失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取收藏列表失败:', error);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			// 加载更多数据
			async loadMore() {
				if (this.loading || this.noMore) return;

				this.loading = true;

				try {
					const data = this.buildRequestParams();
					// console.log("加载要发送的数据",data)
					const response = await getParams('/userFavorites', data);
					// console.log("加载返回值",response)

					if (response.data.code === 200) {
						const newData = response.data.attractions || [];
						if (newData.length > 0) {
							this.attractions = [...this.attractions, ...newData];
						}
						if (newData.length < this.limit) {
							this.noMore = true;
						}
					} else {
						uni.showToast({
							title: response.message || '加载更多失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('加载更多失败:', error);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			// 滚动到底部事件
			onScrollToLower() {
				console.log("上划到底")
				this.loadMore();
			},


			handleCardClick(attractionId) {
				// 跳转到景点详情页
				if (this.isNavigating) return;
				this.isNavigating = true;
				uni.navigateTo({
					url: `/pages/attractionInfo/attractionInfo?id=${attractionId} `,
					complete: () => { //跳转锁
						this.isNavigating = false;
					}
				});
			},

			// 刷新收藏列表
			refreshCollection() {
				this.attractions = [];
				this.lastId = 0;
				this.noMore = false;
				this.fetchCollectionData();
			}
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.refreshCollection();
			uni.stopPullDownRefresh();
		}
	}
</script>

<style lang="scss">
	/* 添加加载动画样式 */
	.loading-spinner {
	  width: 30rpx;
	  height: 30rpx;
	  border: 4rpx solid #f3f3f3;
	  border-top: 4rpx solid #1890ff;
	  border-radius: 50%;
	  animation: spin 1s linear infinite;
	  margin: 0 auto;
	}
	
	@keyframes spin {
	  0% { transform: rotate(0deg); }
	  100% { transform: rotate(360deg); }
	}
	
	.collection-page {
	  padding: 20rpx 24rpx;
	  height: 100vh;
	  box-sizing: border-box;
	  
	  .header {
	    margin-bottom: 30rpx;
	    
	    .title {
	      font-size: 36rpx;
	      font-weight: bold;
	      color: #333;
	    }
	  }
	  
	  .scroll-container {
	    height: calc(100% - 80rpx);
	  }
	  
	  .attraction-grid {
	    display: flex;
	    flex-direction: column;
	    gap: 24rpx;
	  }
	  
	  .grid-row {
	    display: flex;
	    gap: 24rpx;
	  }
	  
	  .grid-item {
	    flex: 1;
	    min-width: 0;
	  }
	  
	  .travel-card {
	    margin-bottom: 0;
	    
	    .card-cover {
	      height: 240rpx;
	    }
	    
	    .card-content {
	      padding: 16rpx;
	      
	      .title {
	        font-size: 28rpx;
	      }
	      
	      .subtitle {
	        font-size: 22rpx;
	      }
	    }
	  }
	  
	  .load-more {
	    padding: 30rpx 0;
	    text-align: center;
	    font-size: 26rpx;
	    color: #999;
	  }
	  
	  .empty-state {
	    display: flex;
	    flex-direction: column;
	    align-items: center;
	    justify-content: center;
	    padding: 100rpx 0;
	    
	    image {
	      width: 300rpx;
	      height: 300rpx;
	      margin-bottom: 30rpx;
	    }
	    
	    text {
	      font-size: 28rpx;
	      color: #999;
	    }
	  }
	}
</style>